package cn.zyx.oa.service;

import cn.zyx.common.entity.Page;
import cn.zyx.common.utils.sys.UserUtils;
import cn.zyx.oa.entity.OaNotify;
import cn.zyx.oa.entity.OaNotifyRecord;
import cn.zyx.oa.mapper.OaNotifyMapper;
import cn.zyx.oa.mapper.OaNotifyRecordMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * 通知通告Service
 *
 * @author zyx
 */
@Service
@Transactional(readOnly = true)
public class OaNotifyService {

    @Autowired
    private OaNotifyRecordMapper oaNotifyRecordMapper;

    @Autowired
    private OaNotifyMapper mapper;

    public OaNotify get(String id) {
        OaNotify entity = mapper.get(id);
        return entity;
    }

    /**
     * 获取通知发送记录
     *
     * @param oaNotify
     * @return
     */
    public OaNotify getRecordList(OaNotify oaNotify) {
        oaNotify.setOaNotifyRecordList(oaNotifyRecordMapper.findList(new OaNotifyRecord(oaNotify)));
        return oaNotify;
    }

    public Page<OaNotify> find(Page<OaNotify> page, OaNotify oaNotify) {
        oaNotify.setPage(page);
        page.setList(mapper.findList(oaNotify));
        return page;
    }

    /**
     * 获取通知数目
     *
     * @param oaNotify
     * @return
     */
    public Long findCount(OaNotify oaNotify) {
        return mapper.findCount(oaNotify);
    }

    @Transactional(readOnly = false)
    public void save(OaNotify oaNotify) {
        mapper.save(oaNotify);

        // 更新发送接受人记录
        oaNotifyRecordMapper.deleteByOaNotifyId(oaNotify.getId());
        if (oaNotify.getOaNotifyRecordList().size() > 0) {
            oaNotifyRecordMapper.insertAll(oaNotify.getOaNotifyRecordList());
        }
    }

    /**
     * 更新阅读状态
     */
    @Transactional(readOnly = false)
    public void updateReadFlag(OaNotify oaNotify) {
        OaNotifyRecord oaNotifyRecord = new OaNotifyRecord(oaNotify);
        oaNotifyRecord.setUser(UserUtils.getUser());
        oaNotifyRecord.setReadDate(new Date());
        oaNotifyRecord.setReadFlag("1");
        oaNotifyRecordMapper.update(oaNotifyRecord);
    }

    public Page<OaNotify> findPage(Page<OaNotify> page, OaNotify oaNotify) {
        oaNotify.setPage(page); // 设置参数
        page.setCount(mapper.findPageCount(oaNotify));
        page.setList(mapper.findList(oaNotify));
        return page;
    }

    public void delete(OaNotify oaNotify) {
        mapper.delete(oaNotify);
    }
}